#include <float.h>
#include <assert.h>
#include "curve.h"
#include "opengl.h"
#include "shader.h"
#include "logger.h"

using namespace goatgfx;

#define DEF_THICKNESS	0.075
#define DEF_SEGM_SUB	3
#define DEF_RING_SUB	6

Curve::Curve()
{
	thickness = DEF_THICKNESS;
	mesh_valid = false;
	lengths_valid = false;

	bbox_valid = false;

	segm_subdiv = DEF_SEGM_SUB;
	ring_subdiv = DEF_RING_SUB;
}

Curve::Curve(const Vector3 *points, int num_points)
{
	thickness = DEF_THICKNESS;
	mesh_valid = false;
	lengths_valid = false;

	bbox_valid = false;

	segm_subdiv = DEF_SEGM_SUB;
	ring_subdiv = DEF_RING_SUB;

	for(int i=0; i<num_points; i++) {
		add_point(points[i]);
	}
}

Curve::Curve(const Vector2 *points, int num_points)
{
	thickness = DEF_THICKNESS;
	mesh_valid = false;
	lengths_valid = false;

	bbox_valid = false;

	segm_subdiv = DEF_SEGM_SUB;
	ring_subdiv = DEF_RING_SUB;

	for(int i=0; i<num_points; i++) {
		add_point(Vector3(points[i].x, points[i].y, 0.0));
	}
}

void Curve::set_name(const char *name)
{
	this->name = name;
}

const char *Curve::get_name() const
{
	return name.c_str();
}

bool Curve::empty() const
{
	return cv.empty();
}

void Curve::set_thickness(float thickness)
{
	this->thickness = thickness;
}

void Curve::set_subdiv(int seg, int ring)
{
	if(seg < 1) seg = 1;
	if(ring < 3) ring = 3;

	segm_subdiv = seg;
	ring_subdiv = ring;
}

void Curve::clear()
{
	mesh_valid = false;
	lengths_valid = false;
	bbox_valid = false;
	cv.clear();
}

void Curve::add_point(const Vector3 &pt)
{
	cv.push_back(pt);
	mesh_valid = false;
	lengths_valid = false;
	bbox_valid = false;
}

Vector3 &Curve::get_point(int idx)
{
	mesh_valid = false;
	lengths_valid = false;
	bbox_valid = false;
	return cv[idx];
}

const Vector3 &Curve::get_point(int idx) const
{
	return cv[idx];
}

int Curve::get_count() const
{
	return (int)cv.size();
}

Vector3 &Curve::operator[] (int idx)
{
	return get_point(idx);
}

const Vector3 &Curve::operator[] (int idx) const
{
	return get_point(idx);
}

void Curve::get_bbox(Vector3 *bbmin, Vector3 *bbmax) const
{
	if(!bbox_valid) {
		this->bbmin = Vector3(FLT_MAX, FLT_MAX, FLT_MAX);
		this->bbmax = -this->bbmin;

		for(size_t i=0; i<cv.size(); i++) {
			for(int j=0; j<3; j++) {
				if(cv[i][j] < this->bbmin[j]) {
					this->bbmin[j] = cv[i][j];
				}
				if(cv[i][j] > this->bbmax[j]) {
					this->bbmax[j] = cv[i][j];
				}
			}
		}
		bbox_valid = true;
	}

	if(bbmin) *bbmin = this->bbmin;
	if(bbmax) *bbmax = this->bbmax;
}

void Curve::normalize()
{
	get_bbox(0, 0);	// force validation of the bounding box

	float len = (bbmax - bbmin).length() * 0.5;
	if(len == 0.0) {
		return;
	}

	for(size_t i=0; i<cv.size(); i++) {
		get_point(i) /= len;
	}
}

Vector3 Curve::get_pos(float t) const
{
	if(cv.empty()) {
		return Vector3(0, 0, 0);
	}
	if(cv.size() == 1 || t <= 0.0) {
		return cv[0];
	}
	if(t >= 1.0) {
		return cv.back();
	}

	t = reparametrize(t);

	int numcv = (int)cv.size();
	int idx0 = t * (numcv - 1);
	int idx1 = idx0 + 1;

	int idx_prev = idx0 <= 0 ? idx0 : idx0 - 1;
	int idx_next = idx1 >= numcv - 1 ? idx1 : idx1 + 1;

	float dt = 1.0 / (float)(numcv - 1);

	float t0 = (float)idx0 * dt;
	float t1 = (float)idx1 * dt;

	t = (t - t0) / (t1 - t0);
	if(t < 0.0) t = 0.0;
	if(t > 1.0) t = 1.0;

	//return catmull_rom_spline(cv[idx_prev], cv[idx0], cv[idx1], cv[idx_next], t);
	return bspline(cv[idx_prev], cv[idx0], cv[idx1], cv[idx_next], t);
}

Vector3 Curve::operator() (float t) const
{
	return get_pos(t);
}

void Curve::draw() const
{
	update_mesh();
	if(!mesh_valid) {
		return;
	}

	mesh.draw();
}


float Curve::reparametrize(float t) const
{
	calc_cvlengths();
	return t;	// TODO
}

void Curve::calc_cvlengths() const
{
	if(lengths_valid || cv.empty()) {
		return;
	}

	length.clear();
	length.resize(cv.size());

	length[0] = 0;
	for(size_t i=1; i<cv.size(); i++) {
		length[i] = length[i - 1] + (cv[i] - cv[i - 1]).length();
	}

	lengths_valid = true;
}

void Curve::update_mesh() const
{
	if(mesh_valid) return;

	if(cv.size() < 2) {
		return;
	}

	mesh.clear();

	int nsub = segm_subdiv * (cv.size() - 1);
	int num_rings = nsub + 1;

	int num_verts = ring_subdiv * num_rings;
	int num_quads = ring_subdiv * nsub;
	int num_tri = num_quads * 2;
	int num_idx = num_tri * 3;

	float *varr = mesh.set_attrib_data(MESH_ATTR_VERTEX, 3, num_verts);
	float *narr = mesh.set_attrib_data(MESH_ATTR_NORMAL, 3, num_verts);
	float *tcarr = mesh.set_attrib_data(MESH_ATTR_TEXCOORD, 2, num_verts);
	unsigned int *idxarr = mesh.set_index_data(num_idx);

	float t = 0.0;
	float dt = 1.0 / (float)(num_rings - 1);

	for(int i=0; i<num_rings; i++) {
		Vector3 p = get_pos(t);
		Vector3 dir = (get_pos(t + dt) - p).normalized();

		Vector3 up = Vector3(0, 0, 1);
		float updotdir = dot_product(up, dir);
		if(1.0 - fabs(updotdir) < 1e-4) {
			up = Vector3(0, 1, 0);
		}
		Vector3 right = cross_product(up, dir).normalized();
		up = cross_product(dir, right);

		for(int j=0; j<ring_subdiv; j++) {
			float u = (float)j / (float)ring_subdiv * M_PI * 2.0;
			Quaternion qrot(dir, u);
			Vector3 v = p + right.transformed(qrot) * thickness;

			*varr++ = v.x;
			*varr++ = v.y;
			*varr++ = v.z;

			Vector3 norm = (v - p).normalized();
			*narr++ = norm.x;
			*narr++ = norm.y;
			*narr++ = norm.z;

			*tcarr++ = u;
			*tcarr++ = t;

			if(i < nsub) {
				int quad = i * ring_subdiv + j;

				int v0 = quad;
				int v1 = i * ring_subdiv + ((j + 1) % ring_subdiv);
				int v2 = (i + 1) * ring_subdiv + ((j + 1) % ring_subdiv);
				int v3 = (i + 1) * ring_subdiv + j;

				idxarr[quad * 6] = v0;
				idxarr[quad * 6 + 1] = v1;
				idxarr[quad * 6 + 2] = v2;

				idxarr[quad * 6 + 3] = v0;
				idxarr[quad * 6 + 4] = v2;
				idxarr[quad * 6 + 5] = v3;
			}
		}

		t += dt;
	}

	mesh_valid = true;
}
